initWS('ws://localhost:8080/poultry/ws/admin/console')
var ws;
var conn = false
function initWS(wsUrl){
	ws = new WebSocket(wsUrl);
	ws.onopen = function(evt) { 
		setRemind('已连接串口控制程序')
		console.log("Connection open...")
	};
	ws.onmessage = function(evt) {
		console.log( "Received Message: " + evt.data)
		var data = evt.data
		if(data == 'poultry-conn-succ'){
			conn = true
			$('#conn-btn').html('连接成功')
		}else if(data.indexOf('poultry-conn-fail') ==0){
			myAlert(data);
		}else if(data.indexOf('poultry-find-succ') ==0){
			var id = data.substring(17)
			loadInfo(id)
			var btn = $('#find-btn') 
			btn.html('查询')
			btn.removeAttr('disabled')
		}else if(data.indexOf('poultry-find-fail') ==0){
			var btn = $('#find-btn') 
			btn.html('查询')
			btn.removeAttr('disabled')
		}
	};
	ws.onclose = function(evt) {
		setWarning('串口控制程序已断开')
		console.log("Connection closed.");
	};
}

function loadInfo(id){
	id = id.replace(/ /g,'')
	console.log('loadInfo :'+id)
	$('#log-panel-content').load('poultryInfo?cardid='+id)
}

function setRemind(remind){
	console.log('setRemind:'+remind)
	$('#warning').text('')
	$('#remind').text(remind)
}

function setWarning(warning){
	console.log('setWarning:'+warning)
	$('#remind').text('')
	$('#warning').text(warning)
}

function getPort(){
	var port = $('#select-port').val()
	if((!port) || port == 'null'){
		console.log('getPort:return:null:'+port)
		return null
	}else{
		console.log('getPort:return:'+port)
		return port
	}
}

function myAlert(text){
	console.log('myAlert:'+text)
	$('#alert-modal-bd').text(text)
	$('#alert-modal').modal('open')
}

$('#conn-btn').on('click',function(e){
	var port = getPort()
	if(!port){
		myAlert('请选择正确的串口')
		return
	}
	
	var btn = e.currentTarget
	var loading = '<i class="am-icon-spinner am-icon-spin"></i>连接中'
	var cssClass = btn.getAttribute('class')
	btn.setAttribute('disabled','disabled')
	btn.innerHTML = loading
	ws.send("poultry-conn:"+port);
})

$('#find-btn').on('click',function(e){
	
	if(!conn){
		myAlert('请先连接')
		return
	}
	
	var btn = e.currentTarget
	var loading = '<i class="am-icon-spinner am-icon-spin"></i>查询中'
	var cssClass = btn.getAttribute('class')
	btn.setAttribute('disabled','disabled')
	btn.innerHTML = loading
	ws.send("poultry-find:");
})

//breakoff-btn
$('#breakoff-btn').on('click',function(e){
	
	if(!conn){
		myAlert('请先连接')
		return
	}
	
	var btn = $('#conn-btn')
	btn.removeAttr('disabled')
	btn.html('连接')
	ws.send("poultry-breakoff:");
})




